//
//  WBHomeViewController.swift
//  Weibo
//
//  Created by cc on 11/07/2017.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit

//原創微博可重用cell id
private let originalCellId = "originalCellId"

//被轉發微博的可重用cell id
private let retweetedCellId = "retweetedCellId"

class WBHomeViewController: WBBaseViewController {

    
    /// 列表視圖模型
    private lazy var listViewModel = WBStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(browsePhoto), name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification), object: nil)
        
    }
    
    
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    ///浏览照片通知监听方法
    @objc private func browsePhoto(n: Notification) {
        //1. 从通知的userInfo 提取参数
        guard let selectedIndex = n.userInfo?[WBStatusCellBrowserPhotoSelectedIndexKey] as? Int, let urls = n.userInfo?[WBStatusCellBrowserPhotoURLsKey] as? [String], let imageViewList = n.userInfo?[WBStatusCellBrowserPhotoImageViewsKey] as? [UIImageView] else {
            return
        }
        
        //2. 展现照片浏览控制器
        let vc = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectedIndex, urls: urls, parentImageViews: imageViewList)
        
        present(vc, animated: true, completion: nil)
        
        
    }
    

    //加载数据
    override func loadData() {
        
//        print("--準備刷新,最后条--   \(self.listViewModel.statusList.last?.text ?? "") ---")
        refreshControl?.beginRefreshing()
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            self.listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
                
                print("--加载数据结束--")
                
                //结束刷新控件
                self.refreshControl?.endRefreshing()
                
                //恢复上拉刷新标记
                self.isPullup = false
                
                //刷新表格
                if shouldRefresh {
                    self.tableView?.reloadData()
                }
            }
        }
    }
    
    //显示好友
    @objc private func showFriends() {
        print(#function)
        
        let vc = WBProfileViewController()
//        vc.hidesBottomBarWhenPushed = true
        //push 的动作是 nav做的
        navigationController?.pushViewController(vc, animated: true)
    }

    
}


// MARK: - 表格数据源方法
extension WBHomeViewController {
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //0.取出視圖模型，根據視圖模型判斷可重用cell
        let vm = listViewModel.statusList[indexPath.row]
        let cellId = (vm.status.retweeted_status != nil) ? retweetedCellId : originalCellId
        
        //1.取cell - 本身會調用代理方法(如果有)/ 如果沒有,找到cell，按照自動佈局的規則從上向下計算，找到向下約束，從而計算動態行高
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WBStatusCell
        
        //2.设置cell
        cell.viewModel = vm
        
        
        //设置代理
        cell.delegate = self

        //3.返回cell
        return cell
    }
    
    
    //父類必須實現代理方法，子類才能重寫，swift 3.0
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //1.根據indexPath獲取視圖模型
        let vm = listViewModel.statusList[indexPath.row]
        //2.返回計算好的行高
        return vm.rowHeight
        
    }
}


// MARK: - WBStatusCellDelegate
extension WBHomeViewController: WBStatusCellDelegate {
    func statusCellDidSelectedURLString(cell: WBStatusCell, urlString: String) {
        
        let vc = WBWebViewController()
        vc.urlString = urlString
        navigationController?.pushViewController(vc, animated: true)
    }
}


// MARK: - 设置界面
extension WBHomeViewController {
    
    //重写父类的方法
    override func setupTableView() {
        
        super.setupTableView()
        
        //设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        //注册原型cell
        tableView?.register(UINib(nibName: "WBStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        tableView?.register(UINib(nibName: "WBStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
        
        
        //设置行高
//        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        
        //取消分隔线
        tableView?.separatorStyle = .none
        
        setupNavTitle()
        
    }
    
    
    /// 设置导航栏标题
    private func setupNavTitle() {
        let title = WBNetworkManager.shared.userAccount.screen_name
        
       let button = WBTitleButton(title: title)
        
        navItem.titleView = button
        
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }
    
    @objc func clickTitleButton(btn: UIButton ) {
        //设置选中状态
        btn.isSelected = !btn.isSelected
       
    }
    
    
    
    
    
}
